﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using SharePointContentGenerator.ContentGeneratorLogic.SharePointWebServiceCopy;
using SharePointContentGenerator.ContentGeneratorLogic.SharePointWebServiceLists;

namespace SharePointContentGenerator.ContentGeneratorLogic.Controllers
{    
    internal class SharePointDocumentLibraryController : SharePointController
    {
        internal const string DOCLIB_NEWCOMMAND = "<Batch OnError=\"Continue\" ListVersion=\"1\"><Method ID=\"1\" Cmd=\"New\"><Field Name=\"ID\">New</Field><Field Name=\"Title\">{0}</Field></Method></Batch>";

        internal SharePointDocumentLibraryController(string siteCollection) : base(siteCollection)
        {
            Contract.Requires(siteCollection != null, "The site collection cannot be null");
            Contract.Requires(siteCollection != string.Empty, "The site collection cannot be string.empty");
        }

        internal SharePointDocumentLibraryController(string siteCollection, string domain, string username, string password) : base(siteCollection, domain, username, password)
        {
            Contract.Requires(siteCollection != null, "The site collection cannot be null");
            Contract.Requires(siteCollection != string.Empty, "The site collection cannot be string.empty");
            Contract.Requires(domain != null, "The domain cannot be null");
            Contract.Requires(username != null, "The username cannot be null");
            Contract.Requires(password != null, "The password cannot be null");
        }

        internal List<string> CreateDocumentLibraries(string baseLibraryName, int numberOfLibraries, bool deleteIfExist)
        {
            Contract.Requires(numberOfLibraries > 0, "The number of libraries cannot be less than 1");
            Contract.Requires(baseLibraryName != null, "The base library name cannot be null");
            Contract.Requires(SiteCollection != null, "The site collection cannot be null");
            Contract.Requires(Username != null, "The username cannot be null");

            List<string> listList = new List<string>();

            ListsSoapClient client = GetListClient();
            for(int counter = 0; counter < numberOfLibraries; counter ++)
            {                
                string listName = baseLibraryName.Trim().Length > 0
                    ? baseLibraryName + counter.ToString()
                    : "Document Library DOCLIB" + counter.ToString();

                string description = "Description for " + listName;

                if (!DoesListAlreadyExist(client, listName))
                {
                    client.AddList(listName, description, 101);
                }
                else
                {
                    if (deleteIfExist)
                    {
                        client.DeleteList(listName);
                        client.AddList(listName, description, 101);
                    }
                }
                listList.Add(listName);
            }

            return listList;
        }

        internal void PopulateLibrariesWithDocuments(List<string> listNameList, int minRandomDocument, int maxRandomdocument)
        {
            Contract.Requires(listNameList != null, "The list of list names cannot be null");
            Contract.Requires(minRandomDocument > 0, "The minimum number of document must be strictly positive");
            Contract.Requires(maxRandomdocument > 0, "The maximum number of document must be strictly positive");
            Contract.Requires(maxRandomdocument > minRandomDocument, "The maximum number of document must be greater than the minimum number of documents");

            Random rand = new Random(DateTime.Now.Second);

            CopySoapClient client = GetCopyclient();

            foreach (string listName in listNameList)
            {
                int numberOfDocumentsToGenerate = rand.Next(minRandomDocument, maxRandomdocument);
                for (int counter = 0; counter < numberOfDocumentsToGenerate; counter++)
                {
                    string newfilename = string.Format("Document_{0}.docx", Guid.NewGuid().ToString().Substring(0, 6));
                    string documentDestinationUrl = string.Format("{0}/{1}/{2}", SiteCollection, listName, newfilename);
                    string[] destinationUrlList = { documentDestinationUrl };

                    CopyResult copyResult = new CopyResult();
                    CopyResult[] copyResults = { copyResult };

                    FieldInformation documentDescriptionFieldInfo = new FieldInformation()
                    {
                        DisplayName = "Description",
                        Type = FieldType.Text,
                        Value = "This is the test description for file " + newfilename

                    };
                    FieldInformation documentTitleFieldInfo = new FieldInformation()
                    {
                        DisplayName = "Title",
                        Type = FieldType.Text,
                        Value = "Autogenerated " + newfilename.Replace(".docx", string.Empty)

                    };
                    FieldInformation[] fieldInfoArray = { documentDescriptionFieldInfo, documentTitleFieldInfo };

                    WordDocumentController docController = new WordDocumentController();
                    MemoryStream objStream = docController.CreateWordDocument();
                    byte[] contentInBytes = new byte[objStream.Length];
                    objStream.Position = 0;
                    objStream.Read(contentInBytes, 0, Convert.ToInt32(objStream.Length));

                    uint copyresult = client.CopyIntoItems(newfilename, destinationUrlList, fieldInfoArray, contentInBytes, out copyResults);

                    string m = copyResults[0].ErrorMessage;
                }
            }
        }
    }
}
